package com.mcglib.flac
{
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.filters.BitmapFilter;
	import flash.filters.ColorMatrixFilter;

	public class FlacUtils
	{
		public function FlacUtils()
		{
		}
		
		public static function getUiInstancesByReg(parentUI:DisplayObjectContainer,nameReg:String,startIndex:int,endIndex:int):Array{
			var arr:Array = new Array;
			for(var i:int = startIndex;i<=endIndex;i++){
				var name:String = nameReg.replace("?",i);
				arr.push(parentUI.getChildByName(name));	
			}
			
			return arr;
		}
		
		public static function removeAllAndAdd(container:DisplayObjectContainer,dis:DisplayObject=null):Array{
			var ra:Array  =  [];
			while(container.numChildren>0){
				ra.push(container.removeChildAt(0));
			}
			
			if(dis){
				container.addChild(dis);
			}
			
			return ra;
		}
		
		public static function contain(dis:DisplayObject,container:DisplayObjectContainer):Boolean{
			var p:DisplayObjectContainer = dis.parent;
			while(p!=null){
				if(p==container)
					return true;
				
				p =p.parent;
			}
			
			return false;
		}
		
		private static var grayFilter:ColorMatrixFilter = new ColorMatrixFilter([0.5,0.5,0.5,0,0,0.5,0.5,0.5,0,0,0.5,0.5,0.5,0,0,0,0,0,1,0]);
		public static function gray(dis:DisplayObject):void{
			for each(var f:BitmapFilter in dis.filters){
				var cmf:ColorMatrixFilter = f as ColorMatrixFilter;
				if(cmf &&　colorMatrixFilterEquals(cmf,grayFilter)){
					return;
				}
			}
			var arr:Array = dis.filters;
			if(arr==null){
				arr = [grayFilter];
			}else{
				arr.push(grayFilter);
			}
			
			dis.filters = arr;
		}
		
		public static function cancelGray(dis:DisplayObject):void{
			var index:int = -1
			var farr:Array = dis.filters;
			if(farr==null || farr.length==0)
				return;
			for(var i:int;i<farr.length;i++){
				if(farr[i] is ColorMatrixFilter)
				{
					var cmf:ColorMatrixFilter  = farr[i] as ColorMatrixFilter;
					if(colorMatrixFilterEquals(cmf,grayFilter)){
						index = i;
						break;
					}
				}
			}
			
			if(index!=-1){
				farr.splice(index,1);
			}
			
			dis.filters = farr;
		}
		
		public static function colorMatrixFilterEquals(f1:ColorMatrixFilter,f2:ColorMatrixFilter):Boolean{
			var arr1:Array = f1.matrix;
			var arr2:Array = f2.matrix;
			if(arr1==arr2)
				return true;
			if(arr1.length!=arr2.length)
				return false;
			
			for(var i:int=0;i<arr1.length;i++){
				if(arr1[i]!=arr2[i])
					return false;
			}
			
			return true;
		}
	}
}

